<?php
/**
 * Exporting to Spreadsheet
 *
 */
class SpreadsheetExport 
{
   public $file;
   public $row;
   
   /**
    * Object constructor
    *
    */
   function SpreadsheetExport()
   {
      $this->file = $this->__BOF();
      $row = 0;
   }

   function __BOF() {
       return pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
   }

   function __EOF() 
   {
       return pack("ss", 0x0A, 0x00);
   }

   function __writeNum($row, $col, $value) 
   {
       $this->file .= pack("sssss", 0x203, 14, $row, $col, 0x0);
       $this->file .= pack("d", $value);
   }

   function __writeString($row, $col, $value ) 
   {
       $L = strlen($value);
       $this->file .= pack("ssssss", 0x204, 8 + $L, $row, $col, 0x0, $L);
       $this->file .= $value;
   }
   
   /**
    * Adds a cell
    *
    * @param string $value cell value
    * @param integer $row cell row
    * @param integer $col cell column
    */
   function WriteCell($value, $row, $col) 
   {
      if(is_numeric($value))
      {
         $this->__writeNum($row, $col, $value);
      }
      elseif(is_string($value))
      {
         $this->__writeString($row, $col, $value);
      }
   }
   
   /**
    * Adds a row
    *
    * @param array $data cells
    * @param integer $row row number
    */
   function AddRow($data, $row=null) 
   {
      //If the user doesn't specify a row, use the internal counter.
      if(!isset($row)) 
      {
         $row = $this->row;
         $this->row++;
      }
      for($i = 0; $i<count($data); $i++) 
      {
         $cell = $data[$i];
         $this->WriteCell($cell,$row,$i);
      }
   }
	
   function CreateFileFromArray(array $data, $path_to_file)
   {
   		foreach ($data as $key=>$value)
   		{
   			$this->AddRow($value);
   		}
   		$this->CreateFile($path_to_file);
   }
   
   /**
	* Creates the file
	*
	* @param string $path_to_file path to the file
   */
   function CreateFile($filename)
   {
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");;
      header("Content-Disposition: attachment;filename=$filename");
      header("Content-Transfer-Encoding: binary ");
      $this->Write($filename);
   }
   
   /**
	* Writes the file
	*
	* @param string $path_to_file path to the file
   */
   function Write($path_to_file) 
   {
   		$file = $this->file.$this->__EOF();
   		$fp = fopen($path_to_file, 'w+');
   		fwrite($fp, $file);
	   	fclose($fp);
   }
}
?>